<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RAG 智能问答系统</title>
    
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Material Icons -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
    
    <!-- Inter 字体 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- 自定义样式 -->
    <link rel="stylesheet" href="css/styles.css">
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'accent-blue': '#A7C7ED',
                        'accent-purple': '#D0BCE1',
                        'accent-pink': '#F4B6C2',
                        'bg-primary': '#E8F0FE',
                        'bg-secondary': '#F0F8FF',
                    }
                }
            }
        }
    </script>
</head>
<body class="h-screen overflow-hidden">
    <!-- 主容器 -->
    <div class="flex h-full">
        <!-- 主内容区 -->
        <main class="flex-1 flex flex-col bg-bg-secondary">
            <!-- 顶部工具栏 -->
            <div class="bg-bg-primary border-b border-accent-blue/20 px-4 py-3">
                <button id="documentsBtn" class="flex items-center gap-2 px-4 py-2 bg-accent-blue/20 border border-accent-blue text-accent-blue font-medium rounded-lg hover:bg-accent-blue hover:text-white transition-all duration-300" style="box-shadow: 0 0 5px rgba(167, 199, 237, 0.5);">
                    <span class="material-symbols-outlined">folder</span>
                    <span>文档管理</span>
                </button>
            </div>
            <!-- 消息显示区 -->
            <div id="messagesContainer" class="flex-1 overflow-y-auto p-4 md:p-6 space-y-6 custom-scrollbar">
                <!-- 欢迎消息 -->
                <div class="flex items-start gap-3 message-enter">
                    <!-- AI头像 -->
                    <div class="w-10 h-10 rounded-full border-2 border-accent-purple flex items-center justify-center bg-white shrink-0" style="box-shadow: 0 0 5px rgba(208, 188, 225, 0.5);">
                        <span class="material-symbols-outlined text-accent-purple">smart_toy</span>
                    </div>
                    
                    <div class="flex-1">
                        <!-- AI名称 -->
                        <div class="text-sm font-bold text-accent-purple mb-1">A.L.I.C.E.</div>
                        
                        <!-- AI消息气泡 -->
                        <div class="bg-white border border-accent-purple/50 rounded-lg px-4 py-3 shadow-md max-w-2xl leading-relaxed markdown-content">
                            <p>你好！我是基于RAG技术的智能助手A.L.I.C.E.。我可以根据已上传的知识库文档回答您的问题。</p>
                            <p>请问有什么我可以帮助您的吗？</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 输入框工具栏 -->
            <div class="bg-bg-primary border-t border-accent-blue/20 px-4 py-4 md:px-6">
                <div class="max-w-2xl mx-auto">
                    <div class="flex items-end gap-2 bg-white border border-accent-blue/50 rounded-lg px-3 py-2 focus-within:border-accent-blue focus-within:shadow-lg transition-all duration-300" style="box-shadow: 0 0 3px rgba(167, 199, 237, 0.3);">
                        <!-- 文本输入框 -->
                        <textarea 
                            id="messageInput" 
                            rows="1" 
                            class="flex-1 resize-none outline-none bg-transparent text-gray-800 placeholder-gray-400"
                            placeholder="Message to A.L.I.C.E...."
                            style="max-height: 150px;"
                        ></textarea>

                        <!-- 按钮组 -->
                        <div class="flex items-center gap-1">
                            <!-- 发送按钮 -->
                            <button id="sendBtn" class="bg-accent-blue text-white px-4 py-2 rounded-lg font-bold hover:shadow-lg transition flex items-center gap-1" style="box-shadow: 0 0 3px rgba(167, 199, 237, 0.5);">
                                <span class="material-symbols-outlined">send</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 加载 API 工具 -->
    <script src="js/api.js"></script>

    <!-- 页面脚本 -->
    <script>
        // DOM 元素
        const messagesContainer = document.getElementById('messagesContainer');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const documentsBtn = document.getElementById('documentsBtn');

        // 自动调整输入框高度
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 150) + 'px';
        });

        // 创建用户消息
        function addUserMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'flex items-start gap-3 justify-end message-enter';
            messageDiv.innerHTML = `
                <div class="flex-1 flex flex-col items-end">
                    <div class="text-sm font-bold text-accent-blue mb-1">User</div>
                    <div class="bg-accent-blue/90 text-white rounded-lg px-4 py-3 max-w-2xl" style="box-shadow: 0 0 5px rgba(167, 199, 237, 0.5);">
                        ${escapeHtml(text)}
                    </div>
                </div>
                <div class="w-10 h-10 rounded-full border-2 border-accent-blue flex items-center justify-center bg-white shrink-0" style="box-shadow: 0 0 5px rgba(167, 199, 237, 0.5);">
                    <span class="material-symbols-outlined text-accent-blue">person</span>
                </div>
            `;
            messagesContainer.appendChild(messageDiv);
            scrollToBottom();
        }

        // 创建AI思考中状态
        function addThinkingMessage() {
            const thinkingDiv = document.createElement('div');
            thinkingDiv.className = 'flex items-start gap-3 message-enter';
            thinkingDiv.id = 'thinking-message';
            thinkingDiv.innerHTML = `
                <div class="w-10 h-10 rounded-full border-2 border-accent-purple flex items-center justify-center bg-white shrink-0" style="box-shadow: 0 0 5px rgba(208, 188, 225, 0.5);">
                    <span class="material-symbols-outlined text-accent-purple">smart_toy</span>
                </div>
                <div class="bg-white border border-accent-purple/50 rounded-lg px-4 py-3 shadow-md flex gap-2">
                    <div class="w-2 h-2 bg-accent-purple rounded-full thinking-dot"></div>
                    <div class="w-2 h-2 bg-accent-purple rounded-full thinking-dot"></div>
                    <div class="w-2 h-2 bg-accent-purple rounded-full thinking-dot"></div>
                </div>
            `;
            messagesContainer.appendChild(thinkingDiv);
            scrollToBottom();
            return thinkingDiv;
        }

        // 创建AI消息（流式显示）
        function createAIMessage() {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'flex items-start gap-3 message-enter';
            messageDiv.innerHTML = `
                <div class="w-10 h-10 rounded-full border-2 border-accent-purple flex items-center justify-center bg-white shrink-0" style="box-shadow: 0 0 5px rgba(208, 188, 225, 0.5);">
                    <span class="material-symbols-outlined text-accent-purple">smart_toy</span>
                </div>
                <div class="flex-1">
                    <div class="text-sm font-bold text-accent-purple mb-1">A.L.I.C.E.</div>
                    <div class="ai-message-content bg-white border border-accent-purple/50 rounded-lg px-4 py-3 shadow-md max-w-2xl leading-relaxed markdown-content"></div>
                </div>
            `;
            messagesContainer.appendChild(messageDiv);
            scrollToBottom();
            return messageDiv.querySelector('.ai-message-content');
        }

        // 滚动到底部
        function scrollToBottom() {
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 发送消息
        async function sendMessage() {
            const text = messageInput.value.trim();
            if (!text) return;

            // 清空输入框
            messageInput.value = '';
            messageInput.style.height = 'auto';

            // 添加用户消息
            addUserMessage(text);

            // 显示思考状态
            const thinkingMsg = addThinkingMessage();

            // 准备AI消息容器
            let aiMessageContent = null;
            let fullResponse = '';

            try {
                await API.streamChat(
                    text,
                    // onToken
                    (token) => {
                        if (!aiMessageContent) {
                            thinkingMsg.remove();
                            aiMessageContent = createAIMessage();
                        }
                        fullResponse += token;
                        aiMessageContent.innerHTML = renderMarkdown(fullResponse);
                        scrollToBottom();
                    },
                    // onContext
                    (contextData) => {
                        console.log('检索到的上下文:');
                        console.log('- 相似度:', contextData.similarity);
                        console.log('- 文本内容:', contextData.content);
                    },
                    // onDone
                    () => {
                        if (thinkingMsg.parentElement) {
                            thinkingMsg.remove();
                        }
                        if (!aiMessageContent) {
                            aiMessageContent = createAIMessage();
                            aiMessageContent.innerHTML = '<p class="text-gray-500">未收到回复</p>';
                        }
                    },
                    // onError
                    (error) => {
                        thinkingMsg.remove();
                        Toast.show('发送消息失败: ' + error.message, 'error');
                    }
                );
            } catch (error) {
                thinkingMsg.remove();
                Toast.show('发送消息失败', 'error');
            }
        }

        // 发送按钮点击
        sendBtn.addEventListener('click', sendMessage);

        // 回车发送（Shift+Enter换行）
        messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 文档管理按钮 - 跳转到文档管理页面
        documentsBtn.addEventListener('click', () => {
            window.location.href = 'documents.html';
        });

        // 页面加载完成
        console.log('RAG 智能问答系统已启动');
    </script>
</body>
</html>

